<template>
  <div>
    <el-drawer title="选择撰稿" :visible.sync="select" direction="rtl" size="50%">
      <seleceDepartment :person="data.writerid" @setCanSee="setCanSee"></seleceDepartment>
      撰稿仅可设置1人，可置空
    </el-drawer>

    <el-descriptions title="官Q稿"  ref="QBody" :column="1" :colon=false style="background-color: white;">
      <el-descriptions-item label="撰稿">：{{writer.name}}</el-descriptions-item>
      <el-descriptions-item label="审核">：<span v-html="shenType(data.shen)"></span></el-descriptions-item>
      <el-descriptions-item label="内容">：</el-descriptions-item>
      <el-descriptions-item label="">
        <div v-html="data.message+'<br><b>软件传媒信息平台自动生成</b>'" style="background-color: aliceblue;"></div>
      </el-descriptions-item>
    </el-descriptions>
    <el-button type="primary" icon="el-icon-edit" size="mini" v-if="canDo(2)" @click="setWriter">编辑授权</el-button>
    <el-button type="primary" icon="el-icon-edit" size="mini" v-if="canDo(1)"
      @click="()=>{this.$router.push(`/write?id=${this.$route.query.id||this.$props.id}&type=q`)}">编辑文字</el-button>
    <el-button type="primary" size="mini" @click="shotPic()">保存为图片</el-button>
    <el-descriptions :title="data.imgurls?'配图':'无配图'" :column="1"></el-descriptions>

    <el-card v-if="data.imgurls">
      <span v-for="o,k in data.imgurls.split(',')" style="position: relative;">
        <img :src="o" width="50%" :key="k">
        <el-tag type="danger" style="position: absolute;left:0" v-show="isImgEdit" @click="delImg(k)">
          删除
        </el-tag>
      </span>
      <br>
    </el-card>

    <input type="file" name="" @change="uploadImg" ref="upimg" style="position: absolute;top:-9999px">
    <el-button type="primary" size="mini" v-show="isImgEdit" @click="$refs.upimg.click()">上传<i
        class="el-icon-upload el-icon--right"></i>
    </el-button>
    <br> 
    <el-button type="primary" icon="el-icon-edit" size="mini" v-if="canDo(2)" @click="setImg">{{isImgEdit?"保存":"编辑配图"}}
    </el-button>
    <br><br>
    <!-- <el-button type="primary" icon="el-icon-refresh" circle></el-button> -->


    <el-dialog title="生成图片" :visible.sync="toimgDialog" width="30%">
      <img :src="toimgUrl" width="100%">
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="toimgDialog = false">关闭</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  import messageApi from "../../api/message.js"
  import userApi from "../../api/user.js"
  import seleceDepartment from "../selectDeparment.vue"
  import Dom2pic from "dom2pic"
  import domtoimage from 'dom-to-image'
  import face from "../../api/face.js"

  export default {
    data() {
      return {
        data: {},
        writer: {},
        canWrite: false,
        select: false,
        isImgEdit: false,
        apiType: "imgbox",
        toimgDialog: false,
        faceType: 1,
        toimgUrl: ""
      }
    },
    props: ['id'],
    methods: {
      refresh() {
        let id=this.$route.query.id||this.$props.id
        messageApi.getQ(id).then((res) => {
          if (res.data.length == 0) {
            this.$emit("hasQ", 0)
            return
          }
          this.$emit("hasQ", id)
          this.data = res.data[0]
          let regex2 = /\{(.+?)\]/g;
          let str = this.data.message
          if (str.match(regex2) != null) {
            for (let emo of str.match(regex2)) {
              str = str.replace(emo, String.fromCodePoint(emo.replace(/\{/, "")
                .replace(/\]/, "")));
            }
          }
          this.data.message = str

          userApi.getUserInfo(res.data[0].writerid).then((res) => {
            this.writer = res.data[0]
          })
        })
        messageApi.getCanUp(id).then((res) => {
          this.canWrite = !!res.data.length
        })
      },
      canDo(num) {
        let result = false
        let userInfo = userApi.getMyInfo()
        if (userInfo.qx >= num && (userInfo.department == 1 || userInfo.department == 0)) {
          result = true
        } else if (num == 1 && (userInfo.department == 1 || userInfo.department == 0)) {
          result = this.canWrite
        }
        return result
      },
      setWriter() {
        this.select = true
      },
      shotPic() {
        if (this.faceType == 1) {
          console.log(this.$refs.QBody)
          let images = this.$refs.QBody.$el.getElementsByTagName('img');
          for (let img of images) {
            console.log(img.src = face.getLocationFace(img.src.replace(/[^-](\d)-|[^\d]/ig, '')))
          }
          this.faceType = 2
        }
        		const option= {
        					width:this.$refs.QBody.$el.offsetWidth, // 高度宽度自行设定
        					height:this.$refs.QBody.$el.offsetHeight,
        					scale:4 // 后面的字表示需要把一个像素转为几个像素
        					}
        const that = this
        const node = this.$refs.QBody.$el // 通过id获取dom
        console.log(node, 'node')
        domtoimage
          .toPng(node, {...option})
          .then((dataUrl) => {
            //输出图片的Base64,dataUrl
            // 下载到PC
            this.toimgDialog = "true"
            this.toimgUrl = dataUrl
            const a = document.createElement('a') // 生成一个a元素
            const event = new MouseEvent('click') // 创建一个单击事件
            a.download = "官Q截图-"+this.data.id // 设置图片名称没有设置则为默认
            a.href = dataUrl // 将生成的URL设置为a.href属性
            a.dispatchEvent(event) // 触发a的单击事件
          })
          .catch(function(error) {
            console.error('oops, something went wrong!', error)
          })
      },
      setImg() {
        if (this.isImgEdit) {

          messageApi.setQImg(this.data.id, this.data.imgurls).then((res) => {
            if (res.code == 1) {
              this.$notify.success({
                title: '成功',
                message: '保存成功'
              });
            }
          })
        }
        this.isImgEdit = !this.isImgEdit
      },
      shenType(type) {
        switch (type) {
          case 0:
            return "未知";
            break;
          case 1:
            return "一审中";
            break;
          case 2:
            return "二审中";
            break;
          case 3:
            return "<b style='color:green'>已通过</b>";
            break;
          case 4:
            return "<b style='color:green'>已发稿</b>";
            break;
          case 5:
            return "<b style='color:red'>驳回</b>";
            break;
        }
      },
      setCanSee(result) {
        if (result.length > 1) {
          this.$notify.error({
            title: '错误',
            message: '撰稿仅可设置1人'
          });
        } else if (result.length == 0) {
          messageApi.setWrite(this.data.id, 0).then((res) => {
            if (res.code == 1) {
              this.$notify.success({
                title: '成功',
                message: '编辑成功'
              });
            }
          })
        } else {
          messageApi.setWrite(this.data.id, result[0].id).then((res) => {
            if (res.code == 1) {
              this.$notify.success({
                title: '成功',
                message: '编辑成功'
              });
            }
          })
        };
        this.refresh()
      },
      delImg(k) {
        console.log(k)
        let imgs = this.data.imgurls.split(",")
        imgs.splice(k, 1)
        this.data.imgurls = imgs.join(",")
      },
      uploadImg() {
        let formData = new FormData();
        formData.append("image", this.$refs.upimg.files[0]);
        this.$notify.info({
          title: '消息',
          message: '上传中，请稍等。'
        });
        this.$axios({
          url: `https://www.hualigs.cn/api/upload?apiType=${this.apiType}&token=dbc28d865eeb34d94772b68fa3f7081d`,
          method: 'POST',
          data: formData,
        }).then((res) => {
          let url = res.data.data.url[this.apiType]
          if (url.indexOf("失败") != -1) {
            this.$notify.error({
              title: '错误',
              message: '上传失败，请重试'
            });
            return
          }
          if (!this.data.imgurls) {
            this.data.imgurls = ""
          }
          let imgs = this.data.imgurls.split(",")
          imgs.push(url)
          this.data.imgurls = imgs.join(",")
        })
      },
    },
    created() {
      setTimeout(this.refresh,10)
    },
    components: {
      seleceDepartment
    }
  }
</script>

<style>
  video{
    max-width: 300px;
  }
</style>
